<?php
namespace app\common\model;
class Member extends Base{
    protected $auto = ['p_path'];
    protected function setPPathAttr($value){
        if(empty($value)){
            return ',';
        }
        return $value;
    }
    /**
     * 聊天组件用户数据获取
     * @param  integer $id 用户ID
     * @return Member
     */
    function wsImData($id){
    	$options=[
    		'with'=>['device','device.software','device.software.social']
    	];
    	$data=$this->read(['id'=>$id,'status'=>1],'id,name,head_img',$options);
    	if(isset($data['head_img'])){
    		$data['head_img']=images($data['head_img']);
    	}
    	return $data;
    }
    // 用于self::wsImData()
    function device(){
    	return $this->hasMany('device','member_id')->field('id,member_id,name,is_busy,id=0 as expand')->order('is_busy');
    }
	function role(){
		return $this->belongsToMany('role');
	}
    
    /**
     * 获取会员级别名称
     * @param  [type] $value [description]
     * @param  [type] $data  [description]
     * @return [type]        [description]
     */
    function getVipTextAttr($value,$data){
        if(isset($data['vip_id'])&&$data['vip_id']>0){
            $rs=model('vip')->read(['id'=>$data['vip_id']],'name');
            return $rs['name'];
        }
        return '';
    }
    /**
     * 父级
     * @param  [type] $value [description]
     * @param  [type] $data  [description]
     * @return [type]        [description]
     */
    function getParentAttr($value,$data){
        if(isset($data['pid'])&&$data['pid']>0){
            $rs=$this->read(['id'=>$data['pid']],'name');
            return $rs['name'];
        }
        return '';
    }
    /**
     * vip 过期
     * @param  integer $id 用户ID
     * @param  boolean $expire 是否强制用户VIP过期
     * @return [type]     [description]
     */
    function isVip($uid,$expire=false){
        $user=$this->read(['id'=>$uid],'vip_expire,vip_level');
        if(!isset($user['vip_expire'])){
            return 0;
        }
        $time=time();
        if($expire||($user['vip_expire']>0&&$user['vip_expire']<=$time)){
            $data=[
                'id'=>$uid,
                'vip_level'=>0,
                'vip_ratio'=>0,
                'vip_level'=>0,
                'vip_id'=>0,
            ];
            if($expire){
                $data['vip_expire']=time();
            }
            $this->edit($data);

            // 设置所有未领取的订单奖励为期限
            $map=[
                'pid'=>$uid,
                'state'=>1,
                'is_gain'=>0,
                'expire_time'=>0,
            ];
            model('order')->edit(['expire_time'=>$time+7*86400],$map);
        }else if($user['vip_expire']>0){
            return $user['vip_level'];
        }
        return 0;
    }
    function city(){
        return $this->belongsTo('district','city_id')->bind(['city'=>'name'])->field('id,name');
    }
    function attr(){
        return $this->belongsToMany('testattr','member_attr','attr_id','uid');
    }
}
